package com.controller;

import com.bean.Announcement;
import com.common.Result;
import com.service.AnnouncementService;
import com.utils.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/announcements")
public class AnnouncementController {
    @Autowired
    private AnnouncementService announcementService;

    /**
     * 根据公告 ID 获取公告信息
     * @param announcementId 公告的唯一标识
     * @return 封装了公告信息的通用结果对象，包含状态码、消息和数据
     */
    @GetMapping("/{announcementId}")
    public Result<Announcement> getAnnouncementById(@PathVariable Integer announcementId) {
        Announcement announcement = announcementService.getAnnouncementById(announcementId);
        if (announcement != null) {
            return Result.success(announcement);
        }
        return Result.fail("公告信息不存在");
    }

    /**
     * 分页模糊查询公告信息，可根据公告标题、内容或发布者用户名进行模糊匹配
     * @param keyword 模糊查询关键字，可匹配公告标题、内容或发布者用户名
     * @param pageNum 当前页码
     * @param pageSize 每页记录数
     * @return 封装了分页公告信息的通用结果对象，包含状态码、消息和数据
     */
    @GetMapping
    public Result<PageInfo<Announcement>> getAnnouncementsWithKeyword(
            @RequestParam(required = false) String keyword,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize) {
        PageInfo<Announcement> pageInfo = announcementService.getAnnouncementsWithKeyword(keyword, pageNum, pageSize);
        return Result.success(pageInfo);
    }

    /**
     * 插入新的公告信息
     * @param announcement 公告信息对象
     * @return 封装了插入结果的通用结果对象，包含状态码、消息和插入是否成功的标志
     */
    @PostMapping
    public Result<Boolean> insertAnnouncement(@RequestBody Announcement announcement) {
        boolean result = announcementService.insertAnnouncement(announcement);
        if (result) {
            return Result.success(true);
        }
        return Result.fail("插入公告信息失败");
    }

    /**
     * 根据公告 ID 更新公告信息
     * @param announcement 公告信息对象，包含要更新的内容，announcementId 用于定位记录
     * @return 封装了更新结果的通用结果对象，包含状态码、消息和更新是否成功的标志
     */
    @PutMapping
    public Result<Boolean> updateAnnouncement(@RequestBody Announcement announcement) {
        boolean result = announcementService.updateAnnouncement(announcement);
        if (result) {
            return Result.success(true);
        }
        return Result.fail("更新公告信息失败，公告可能不存在");
    }

    /**
     * 根据公告 ID 删除公告信息
     * @param announcementId 公告的唯一标识
     * @return 封装了删除结果的通用结果对象，包含状态码、消息和删除是否成功的标志
     */
    @DeleteMapping("/{announcementId}")
    public Result<Boolean> deleteAnnouncementById(@PathVariable Integer announcementId) {
        boolean result = announcementService.deleteAnnouncementById(announcementId);
        if (result) {
            return Result.success(true);
        }
        return Result.fail("删除公告信息失败，公告可能不存在");
    }
}